#pragma once
#include <memory>
#include <functional>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstring>
#include <unordered_map> // 添加这个

class TcpConnection;
class ThreadPool;

using TcpConnectionPtr = std::shared_ptr<TcpConnection>;

class TcpServer
{
public:
    TcpServer(int port, ThreadPool *thread_pool);
    ~TcpServer();

    void start();
    void stop();
    void setConnectionCallback(std::function<void(TcpConnectionPtr)> cb);
    void setMessageCallback(std::function<void(TcpConnectionPtr, const std::string &)> cb);
    void setCloseCallback(std::function<void(TcpConnectionPtr)> cb);

private:
    void handleAccept();
    void handleEvents();
    void addFd(int epoll_fd, int fd, uint32_t events);
    void removeFd(int epoll_fd, int fd);
    void setNonBlocking(int fd);

    int _port;
    int _listen_fd;
    int _epoll_fd;
    bool _running;
    ThreadPool *_thread_pool;

    std::function<void(TcpConnectionPtr)> _connection_callback;
    std::function<void(TcpConnectionPtr, const std::string &)> _message_callback;
    std::function<void(TcpConnectionPtr)> _close_callback;

    // 添加这个：保存所有活跃的连接
    std::unordered_map<int, TcpConnectionPtr> _connections;
};